<template>
    <v-coreLayout ref="coreLayout" :step="0" :countdownTime="300">
        <template slot="content">
            <v-exception ref="exceptionModel"></v-exception>
            <v-preProcessModel ref="preProcessModel"></v-preProcessModel>
            <Modal v-model="scanFinalModel" width="800px" :closable="false" :mask-closable="false">
                <p slot="header" style="color:#19be6b;text-align:center">
                    <Icon type="ios-information-circle"></Icon>
                    <span>成功</span>
                </p>
                <div style="text-align:center">
                    <p style="text-align:center;font-size: 18px;margin-bottom: 10px">{{finishRemark}}</p>
                    <p style="text-align:center;font-size: 14px;margin-bottom: 10px">请勿忘记您的U盘、背包或其他个人物品，感谢为您服务，下次再见！</p>
                    <img src="../images/scanner-success.png" width="200" style="margin: 30px">
                </div>
                <div slot="footer">
                    <p style="text-align:center;font-size: 14px;margin-bottom: 10px">我们将在
                        {{this.$root.countdownReturnTime}} s后返回开始页面</p>
                </div>
            </Modal>
            <Modal v-model="usbCopyMode" width="800px" :closable="false" :mask-closable="false">
                <p slot="header" style="color:#19be6b;text-align:center">
                    <Icon type="ios-information-circle"></Icon>
                    <span>USB设备传输</span>
                </p>
                <div style="text-align:center">
                    <img src="../images/USB_notice.gif" width="220" style="margin: 10px"/>
                    <h2>请插入您的U盘，设备将自动拷贝文件至您的USB设备</h2>
                    <h3>Please insert your USB drive, the device will automatically copy files to your USB device</h3>
                    <p style="margin: 10px;font-size: 16px">{{usbCopyState}}</p>
                </div>
                <div slot="footer">
                    <v-list-item>
                    <Button type="warning" style="font-size:18px;height: 45px" v-on:click="cancelListenUSBInsertion()">
                        <Icon type="md-exit"/>
                        回退 / Back
                    </Button>
                    <div @click="ex()">
                        <v-countdownButton ref="countdown" ></v-countdownButton>
                    </div>
                </v-list-item>
                </div>
            </Modal>
            <Modal v-model="qrCodeMode" width="800px" :closable="false" :mask-closable="false">
                <p slot="header" style="color:#19be6b;text-align:center">
                    <Icon type="ios-information-circle"></Icon>
                    <span>扫描“码上”下</span>
                </p>
                <div style="text-align:center">
                    <div ref="downloadQRCode" style="display: flex;justify-content: center;margin: 10px"></div>
                    <Spin fix v-if="loading_QR">
                        <Icon type="ios-loading" size=50 class="spin-icon-load"></Icon>
                        <div>上传扫描文件中</div>
                        <div>服务器在二维码生成后10分钟后将删除文件，请尽快取回。</div>
                    </Spin>
                    <h2>请扫描二维码下载您的扫描文件图片，文件将在10分钟删除，请尽快取回!</h2>
                    <h3>Please scan QR code to download your scanned file image. The file will be deleted in 10 minutes. Please retrieve it as soon as possible!</h3>
                </div>
                <div slot="footer">
                    <Button type="success" style="font-size:18px;height: 45px" v-on:click="finalSuccess()">
                        <Icon type="md-exit"/>
                        完成 / Finish
                    </Button>
                </div>
            </Modal>
            <Modal v-model="scanFinishModel" width="800px" :closable="false" :mask-closable="false">
                <p slot="header" style="color:#19be6b;text-align:center">
                    <Icon type="ios-information-circle"></Icon>
                    <span>扫描结束</span>
                </p>
                <div style="display: flex;flex-direction: column;align-items: center">
                    <h2>请选择扫描文件下载方式</h2>
                    <h3>Please select download method of scan file</h3>
                    <div style="display: flex;margin: 10px;">
                        <Card v-on:click.native="doUploadCopyFile()"
                              style="width: 200px;margin:20px;">
                            <div style="text-align:center">
                                <img src="../images/scan_upload.png" height="90">
                                <h2>“码”上下载</h2>
                                <h3>QR Code Download</h3>
                            </div>
                        </Card>
                        <Card v-on:click.native="startUSBListening()"
                              style="width: 200px;margin:20px;">
                            <div style="text-align:center">
                                <img src="../images/scan_usb.png" height="90">
                                <h2>U盘拷贝</h2>
                                <h3>USB Device Copy</h3>
                            </div>
                        </Card>
                        <Card v-on:click.native="finishScan('copy')"
                              style="width: 200px;margin:20px;">
                            <div style="text-align:center">
                                <img src="../images/scan_copy.png" height="90">
                                <h2>复印</h2>
                                <h3>Duplicate</h3>
                            </div>
                        </Card>
                    </div>
                </div>
                <div slot="footer">
                    <v-countdownButton ref="countdown"></v-countdownButton>
                </div>
            </Modal>
            <Modal v-model="scanSuccessModel" width="800px" :closable="false" :mask-closable="false">
                <p slot="header" style="color:#19be6b;text-align:center">
                    <Icon type="ios-information-circle"></Icon>
                    <span>成功</span>
                </p>
                <div style="display: flex;flex-direction: column;align-items: center">
                    <h2>扫描任务已经顺利完成</h2>
                    <h3>Scan task completed successfully</h3>
                    <p style="margin: 10px;font-size: 16px">若您需要继续扫描，请装入文件并点击继续扫描，否则请点击我已完成扫描。<br/>
                        If you need to continue scanning, please load the file and click continue, otherwise click complete.
                    </p>
                    <img src="../images/scanner-success.png" width="200" style="margin: 20px">
                </div>
                <div slot="footer">
                    <Button type="success" style="font-size:18px;height: 45px" v-on:click="doScan()" size="large">
                        <Icon type="ios-paper"/>
                        继续扫描 / Continue
                    </Button>
                    <Button type="success" style="font-size:18px;height: 45px" v-on:click="finishScan()" size="large">
                        <Icon type="ios-paper"/>
                        我已完成扫描 / Complete
                    </Button>
                    <v-countdownButton ref="countdown"></v-countdownButton>
                </div>
            </Modal>
            <Modal v-model="scanStartModel" width="900px" :closable="false" :mask-closable="false"
                   v-on:click.native="countdownReset()">
                <p slot="header" style="color:#2d8cf0;text-align:center">
                    <Icon type="ios-information-circle"></Icon>
                    <span>装入扫描文件并开始扫描</span>
                </p>
                <div style="display: flex;flex-direction: column;align-items: center">
                    <h2>请准备并装入需要扫描或复印的文件</h2>
                    <h3>Please load the documents that need to be scanned or copied</h3>
                    <p style="margin: 10px;font-size: 16px">
                        请将需扫描的文稿按图示放入ADF自动进稿器（左图）或平板扫描器（右图），并确认位置正确。书本等已经装订的材料禁止使用ADF，请根据文档辅助线将原稿正面向下放在平板扫描器的左上角。
                        <br/>
                        Please put the documents to be scanned into ADF (left picture) or flat scanner (right picture)
                        as shown in the figure, and make sure the position is correct. It is forbidden to use ADF for
                        binding materials such as books. Please place the front of the original in the top left corner
                        of the flat scanner according to the document guide line.
                    </p>
                    <img src="../images/scanner.png" width="600" style="margin: 10px">
                </div>
                <div slot="footer">
                    <Button type="success" style="font-size:18px;height: 45px" v-on:click="doScan()" size="large">
                        <Icon type="ios-paper"/>
                        开始扫描 / Start
                    </Button>
                    <v-countdownButton ref="countdown"></v-countdownButton>
                </div>
            </Modal>

            <Row style="height: 100%" type="flex">
                <Col span="24"
                     style="display:flex;justify-content:center;flex-direction:column;padding-left: 90px;padding-right: 90px;height: 100%">
                    <div style="display: flex;align-items: flex-end;margin-bottom: 30px">
                        <img src="../images/scanner-default.svg" width="120">
                        <Icon type="ios-loading" size=25 class="spin-icon-load"></Icon>
                        <p style="font-size: 18px;margin-left:10px">[ {{state}} ]</p>
                    </div>

                    <p style="font-size: 20px">海内存知己，天涯若比邻</p>
                    <p style="font-size: 36px">我们将很快完成<span style="font-size: 28px" v-if="this.state === '正在扫描'">（预计已打印完成 {{pseudoProgress}} %，剩余打印时间 {{remainingTime}} 秒）</span>
                    </p>
                    <br/>
                    <p style="font-size: 18px">预估的打印时间可能与实际时间不符，以实际扫描进度为准</p>
                </Col>
            </Row>
        </template>
    </v-coreLayout>
</template>
<script>
    import * as axios from "axios";
    import ExceptionModel from '../components/ExceptionModel.vue';
    import CountdownButton from '../components/CountdownButton.vue';
    import PreProcessModel from '../components/PreProcessModel.vue';
    import CoreLayout from '../components/CoreLayout.vue';
    import QRCode from 'qrcodejs2';

    export default {
        components: {
            'v-exception': ExceptionModel,
            'v-countdownButton': CountdownButton,
            'v-preProcessModel': PreProcessModel,
            'v-coreLayout': CoreLayout,
        },
        data() {
            return {
                processCountdownClock: 0,
                state: "等待设备初始化",
                scanStartModel: false,
                scanSuccessModel: false,
                estimatedTime: 18,
                remainingTime: null,
                pseudoProgress: 0,
                scanFinishModel: false,
                scanFinalModel: false,
                qrCodeUrl: null,
                qrCodeMode: false,
                loading_QR: false,
                usbCopyMode: false,
                finishRemark: "扫描任务已经全部完成",
                usbCopyState: "等待USB插入中……",
                usbListeningSource: {},
            }
        },
        mounted() {
            this.scanStartModel = true;
            this.$refs.countdown.countDownStart(300);
        },
        methods: {
            countdownReset() {
                this.$refs.countdown.countdownReset(300);
            },
            showScanSuccessPage() {
                this.scanSuccessModel = true;
                this.$refs.countdown.countDownStart(300);
            },
            //此处修改过
            finishScan(type) {
                if(type!==undefined)
                this.$root.mode=type;
                if (this.$root.mode == "scan") {
                    this.$refs.countdown.countDownStart(300);
                    this.scanSuccessModel = false;
                    this.scanFinishModel = true;
                } else {
                    this.closeAllModel();
                    this.$refs.preProcessModel.copyFileProcessing(this);
                }
            },
            doScan() {
                clearInterval(this.$root.countdownClock);
                this.scanStartModel = false;
                this.scanSuccessModel = false;
                this.remainingTime = this.estimatedTime;
                this.state = "正在扫描";
                this.processCountdownClock = window.setInterval(() => {
                    this.remainingTime--;
                    this.pseudoProgress = Math.floor(((estimatedTime - this.remainingTime) / estimatedTime) * 100);
                    if (this.remainingTime === 0) {
                        clearInterval(this.processCountdownClock);
                    }
                }, 1000);
                axios({
                    method: 'get',
                    url: 'http://localhost:8999/runningScanner',
                    params: {
                        printUserMark: this.$root.printUserMark,
                    }
                }).then((response) => {
                    let responseData = response.data;
                    clearInterval(this.processCountdownClock);
                    if (responseData.state == "SUCCESS") {
                        this.state = "扫描已经结束";
                        this.pseudoProgress = 100;
                        this.showScanSuccessPage();
                    } else {
                        this.state = "扫描已经终止";
                        this.pseudoProgress = 5;
                        this.closeAllModel();
                        this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, responseData.msg, responseData.code, responseData.state);
                    }
                }).catch((reason) => {
                    this.closeAllModel();
                    this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, reason.toString());
                });
            },
            doUploadCopyFile() {
                this.countdownReset();
                this.scanFinishModel = false;
                this.qrCodeMode = true;
                this.loading_QR = true;
                axios({
                    method: 'get',
                    url: 'http://localhost:8999/uploadCopyFileToServer',
                    params: {
                        printUserMark: this.$root.printUserMark,
                    }
                }).then((response) => {
                    let responseData = response.data;
                    if (responseData.state == "SUCCESS") {
                        this.getQRCodePic();
                    } else {
                        this.closeAllModel();
                        this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, responseData.msg, responseData.code, responseData.state);
                    }
                }).catch((reason) => {
                    this.closeAllModel();
                    this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, reason.toString());
                });
            },
            //此处删除了this.axios.CancelToken.source()的停用功能
            startUSBListening() {
                this.countdownReset();
                this.scanFinishModel = false;
                this.usbCopyMode = true;
                this.usbListeningSource = axios.CancelToken.source();
                axios({
                    method: 'get',
                    url: 'http://localhost:8999/listenUSBInsertion',
                    cancelToken: this.usbListeningSource.token,
                }).then((response) => {
                    let responseData = response.data;
                    console.log(responseData);
                    if (responseData.state == "SUCCESS") {
                        //USB设备成功接入
                        console.log("USB Device Connection Successful");
                        this.usbCopyState = "USB设备已识别，文件拷贝中……"
                        axios({
                            method: 'get',
                            url: 'http://localhost:8999/copyFileToUSB',
                            params: {
                                printUserMark: this.$root.printUserMark,
                                fileCopyPath: JSON.parse(responseData.msg)[0] + "MotaScanFile/",
                            }
                        }).then((response) => {
                            let responseData = response.data;
                            if (responseData.state == "SUCCESS") {
                                this.finishRemark = "文件已拷贝至USB设备/MotaScanFile文件夹中";
                                this.finalSuccess();
                            } else {
                                this.closeAllModel();
                                this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, responseData.msg, responseData.code, responseData.state);
                            }
                        }).catch((reason) => {
                            this.closeAllModel();
                            this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, reason.toString());
                        });
                    }
                }).catch((reason) => {
                    if (reason.message != 'Stop') {
                        this.closeAllModel();
                        this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, reason.toString());
                    }
                });
            },
            cancelListenUSBInsertion() {
                this.usbCopyMode = false;
                this.scanFinishModel = true;
                this.usbListeningSource.cancel('Stop');
            },
            ex() {
                this.usbListeningSource.cancel('Stop');
            },
            getQRCodePic() {
                new QRCode(this.$refs.downloadQRCode, {
                    text: this.$root.serverUrl + this.$root.userDownloadScanFilePageUrl + "?printUserMark=" + this.$root.printUserMark + "&deviceID=" + this.$root.deviceID,
                    width: 100,
                    height: 100,
                    colorDark: "#333333", //二维码颜色
                    colorLight: "#ffffff", //二维码背景色
                    correctLevel: QRCode.CorrectLevel.L//容错率，L/M/H
                })
                this.loading_QR = false;
            },
            finalSuccess() {
                this.scanFinalModel = true;
                this.qrCodeMode = false;
                this.usbCopyMode = false;
                this.countdownReturnTime = 20;
                this.$refs.countdown.countDownStart(10, "/", false);
            },
            closeAllModel() {
                this.scanStartModel = false;
                this.scanSuccessModel = false;
                this.scanFinishModel = false;
                this.scanFinalModel = false;
                this.qrCodeMode = false;
                this.usbCopyMode = false;
            },
        }
    }
</script>